joApps.PrefManager = {

	id: 'PrefManager',
	
	menubar: {
		'PrefManager': {
			'About PrefManager': 'joApps.PrefManager.about()',
			'Export Preferences': 'joPrefManager.uninit()',
		},
	},

	win: null,

	onload: function(){
		joCore.IO.load('css', 'apps/PrefManager/PrefManager.app.css');
	},
	
	start: function(){
		this.win = joCore.UI.window({
			width: 500,
			height: 500,
			application: this.id,
			top: 20,
			left: 20,
			title: 'PrefManager',
		});
		
		var results = [];
		
		this.win.setContent(document.createElement('ul'));
		this.win.addContent('<button class="button-apply">適用</button>');
		joEvent.addEvent($C('button-apply', this.win.display.content), 'click', this.apply, false, this, true);
		
		Deferred.loop(joAppManager.apps.length, function(i){
			//読み込み
			var app = joAppManager.apps[i];
		
			return joCore.IO.read('apps/' + app + '/Pref.html').
			next(function(req){
				var tab = uuQuery.tag('ul', joApps.PrefManager.win.display.content)[0];
				tab.innerHTML += '<li tabpanel="pref-' + app + '">' + app + '</li>';
				joApps.PrefManager.win.display.content.innerHTML += '<div id="pref-' + app + '">' + req.responseText + '</div>';
			}).error(function(){});
		}).next(function(){
			//インターフェース構築
			joApps.PrefManager.tab = new joCore.UI.tab(uuQuery.tag('ul', joApps.PrefManager.win.display.content)[0]);
			
			//値変更時の挙動とデフォルト値を設定する
			var prefboxes = uuQuery('[preference]', joApps.PrefManager.win.display.content);
			prefboxes.forEach(function(prefbox){
				joEvent.addEvent(prefbox, 'change', joApps.PrefManager.onPrefChange, false, joApps.PrefManager);
				joCore.Node.setFormValue(prefbox, joPrefManager.getValue(prefbox.getAttribute('preference')) || '');
			});
			
		}).error(function(e){joCore.logger.error(e);});
	},
	
	
	onPrefChange: function(event){
		var prefbox = event.target;
		joPrefManager.setValue(prefbox.getAttribute('preference'), joCore.Node.getFormValue(prefbox));
	},
	
	
	apply: function(event){
		joEvent.fireEvent('joPrefApply', window);
	},

};